package com.ds.filter;

import com.ds.model.AjaxResult;
import com.ds.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/*")
public class AuthenticationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 请求分两种
     * 1.需要认证后才能访问的请求，除了第二种都是第一种
     * 2.不需要认证直接可以访问的请求。登录页面、登录接口都属于这一类
     *
     * @param request  the <code>ServletRequest</code> object contains the client's request
     * @param response the <code>ServletResponse</code> object contains the filter's response
     * @param chain    the <code>FilterChain</code> for invoking the next filter or the resource
     * @throws IOException
     * @throws ServletException
     */

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        // 获取当前请求的URI获取请求路径
        String requestURI = req.getRequestURI();

        //将不需要认证就能访问的地址挑出来
        if (requestURI.contains("login") || requestURI.endsWith(".js") || requestURI.endsWith(".css")) {
            //不需要认证直接放行
            chain.doFilter(request, response);
        } else {
            //说明当前用户需要登录才能访问
            //从当前用户中获取到登录用户
            HttpSession session = req.getSession();
            //从session中获取当前登录用户是否登录
            User loginUser = (User) session.getAttribute("loginUser");

            if (loginUser == null) {
                //说明当前用户没有登录

                String requestedWith = ((HttpServletRequest) request).getHeader("X-Requested-With");
                String contentType = ((HttpServletRequest) request).getHeader("Content-Type");

                //判断当前请求是否是ajax请求
                HttpServletResponse servletResponse = (HttpServletResponse) response;

                if (contentType != null && contentType.equalsIgnoreCase("application/json;charset=utf-8")) {
                //if (contentType.equalsIgnoreCase("application/json")) {
                    //说明是ajax请求ajax请求 然后返回一个JSON告诉前端未登录
                    servletResponse.setContentType("application/json;charset=utf-8");
                    servletResponse.getWriter().write(new ObjectMapper().writeValueAsString(AjaxResult.error("用户未登录，请先登录")));
                } else {
                    //说明前端是一个网页请求 则进行网页跳转到login.html页面
                    servletResponse.sendRedirect("/ds/login.html");

                }
            } else {
                //说明当前用户已经登录 直接放行
                chain.doFilter(request, response);
            }
        }

    }
}
